﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using calculation.Models;

namespace calculation.Controllers
{
    public class DetalController : Controller
    {
        private DataManager _dataManager;
        public DetalController(DataManager dataManager)
        {
            _dataManager = dataManager;
        }

        public ActionResult List()
        {
            ViewData["Name"] = "Справочник деталей";
            ViewData["Detals"] = _dataManager.Detals.GetDetals();
            return View();
        }

        public ActionResult Detal(int id)
        {
            ViewData.Model = _dataManager.Detals.GetDetals(id);
            return View();
        }
        public ActionResult Delete(int id)
        {
            _dataManager.Detals.DeleteDetal(id);

            return RedirectToAction("List");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Detal d = _dataManager.Detals.GetDetals(id);
            ViewData.Model = d;

            SetEditLists(d);
            return View();
        }

        private void SetEditLists(Detal d)
        {
            ViewData["States"] = new SelectList(_dataManager.States.GetStates(),
                   "StateId", "Title");
            ViewData["Users"] = new SelectList(_dataManager.Membership.GetUsers(),
                "ProviderUserKey", "UserName");

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Detal d)
        {
            if (d.NameDetal.Length <= 3)
                ModelState.AddModelError("Name", "Введите название больше 3 символов");


            if (ModelState.IsValid)
            {
                d.DetalId = id;
                _dataManager.Detals.UpdateDetal(d);
                return RedirectToAction("List");

            }
            SetEditLists(d);
            return View();

        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Add()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(string nameDetal,string typeDetal)
        {
            if (nameDetal.Length <= 3)
                ModelState.AddModelError("Name", "Введите название больше 3 символов");
            if (typeDetal.Length <= 3)
                ModelState.AddModelError("Name", "Введите тип детали больше 3 символов");


            if (ModelState.IsValid)
            {
                _dataManager.Detals.CreateDetal(nameDetal, typeDetal);
                return RedirectToAction("List");
            }
            return View();
        }

    }
}
